<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>存款目标计算器</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link
      href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css"
      rel="stylesheet"
    />
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <link
      href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap"
      rel="stylesheet"
    />

    <script>
      tailwind.config = {
        theme: {
          extend: {
            colors: {
              primary: '#165DFF',
              secondary: '#36D399',
              accent: '#FFAB00',
              neutral: '#3D4451',
              'base-100': '#FFFFFF'
            },
            fontFamily: {
              inter: ['Inter', 'sans-serif']
            }
          }
        }
      }
    </script>

    <style type="text/tailwindcss">
      @layer utilities {
        .content-auto {
          content-visibility: auto;
        }
        .card-shadow {
          box-shadow:
            0 10px 15px -3px rgba(0, 0, 0, 0.1),
            0 4px 6px -2px rgba(0, 0, 0, 0.05);
        }
        .input-focus {
          @apply focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-200;
        }
        .btn-hover {
          @apply hover:shadow-lg transform hover:-translate-y-0.5 transition-all duration-200;
        }
      }
    </style>
  </head>
  <body class="font-inter bg-gray-50 text-neutral min-h-screen flex flex-col">
    <!-- 导航栏 -->
    <nav class="bg-white shadow-sm sticky top-0 z-10">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
          <div class="flex items-center">
            <i class="fa fa-line-chart text-primary text-2xl mr-2"></i>
            <span class="font-bold text-xl text-primary">财务规划助手</span>
          </div>
          <div class="flex items-center space-x-4">
            <button
              class="text-gray-600 hover:text-primary px-3 py-2 rounded-md text-sm font-medium transition-colors duration-200"
            >
              <i class="fa fa-question-circle mr-1"></i> 帮助
            </button>
            <button
              class="text-gray-600 hover:text-primary px-3 py-2 rounded-md text-sm font-medium transition-colors duration-200"
            >
              <i class="fa fa-history mr-1"></i> 历史
            </button>
            <button
              class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-md text-sm font-medium transition-colors duration-200 btn-hover"
            >
              <i class="fa fa-user-circle mr-1"></i> 登录
            </button>
          </div>
        </div>
      </div>
    </nav>

    <!-- 主内容区 -->
    <main class="flex-grow">
      <div class="max-w-7xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
        <!-- 页面标题 -->
        <div class="text-center mb-10">
          <h1 class="text-[clamp(2rem,5vw,3rem)] font-bold text-neutral mb-4">存款目标计算器</h1>
          <p class="text-gray-600 max-w-2xl mx-auto text-lg">
            设定您的财务目标，规划储蓄计划，实现财务自由
          </p>
        </div>

        <!-- 计算器卡片 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
          <!-- 输入表单卡片 -->
          <div class="lg:col-span-2">
            <div class="bg-white rounded-xl shadow-lg p-6 md:p-8 card-shadow">
              <h2 class="text-xl font-bold text-neutral mb-6 flex items-center">
                <i class="fa fa-calculator text-primary mr-2"></i> 输入您的储蓄信息
              </h2>

              <form id="savings-form" class="space-y-6">
                <!-- 存款目标 -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label for="goal-amount" class="block text-sm font-medium text-gray-700 mb-1"
                      >存款目标金额 (元)</label
                    >
                    <div class="relative">
                      <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-gray-500">
                        <i class="fa fa-rmb"></i>
                      </span>
                      <input
                        type="number"
                        id="goal-amount"
                        name="goal-amount"
                        min="0"
                        step="100"
                        value="100000"
                        class="pl-10 block w-full rounded-md border-gray-300 shadow-sm focus:outline-none input-focus py-3 px-4 border"
                      />
                    </div>
                  </div>

                  <div>
                    <label
                      for="current-savings"
                      class="block text-sm font-medium text-gray-700 mb-1"
                      >当前已存金额 (元)</label
                    >
                    <div class="relative">
                      <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-gray-500">
                        <i class="fa fa-rmb"></i>
                      </span>
                      <input
                        type="number"
                        id="current-savings"
                        name="current-savings"
                        min="0"
                        step="100"
                        value="0"
                        class="pl-10 block w-full rounded-md border-gray-300 shadow-sm focus:outline-none input-focus py-3 px-4 border"
                      />
                    </div>
                  </div>
                </div>

                <!-- 月存款和年利率 -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label
                      for="monthly-contribution"
                      class="block text-sm font-medium text-gray-700 mb-1"
                      >每月存款金额 (元)</label
                    >
                    <div class="relative">
                      <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-gray-500">
                        <i class="fa fa-rmb"></i>
                      </span>
                      <input
                        type="number"
                        id="monthly-contribution"
                        name="monthly-contribution"
                        min="0"
                        step="50"
                        value="2000"
                        class="pl-10 block w-full rounded-md border-gray-300 shadow-sm focus:outline-none input-focus py-3 px-4 border"
                      />
                    </div>
                  </div>

                  <div>
                    <label
                      for="annual-interest"
                      class="block text-sm font-medium text-gray-700 mb-1"
                      >预计年利率 (%)</label
                    >
                    <div class="relative">
                      <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-gray-500">
                        <i class="fa fa-percent"></i>
                      </span>
                      <input
                        type="number"
                        id="annual-interest"
                        name="annual-interest"
                        min="0"
                        max="20"
                        step="0.1"
                        value="3.0"
                        class="pl-10 block w-full rounded-md border-gray-300 shadow-sm focus:outline-none input-focus py-3 px-4 border"
                      />
                    </div>
                  </div>
                </div>

                <!-- 目标时间和复利方式 -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label for="timeframe" class="block text-sm font-medium text-gray-700 mb-1"
                      >目标时间 (年)</label
                    >
                    <div class="relative">
                      <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-gray-500">
                        <i class="fa fa-calendar"></i>
                      </span>
                      <input
                        type="number"
                        id="timeframe"
                        name="timeframe"
                        min="0.1"
                        step="0.1"
                        value="5"
                        class="pl-10 block w-full rounded-md border-gray-300 shadow-sm focus:outline-none input-focus py-3 px-4 border"
                      />
                    </div>
                  </div>

                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">复利计算方式</label>
                    <div class="grid grid-cols-3 gap-2">
                      <div class="relative">
                        <input
                          type="radio"
                          id="compound-monthly"
                          name="compound-frequency"
                          value="monthly"
                          checked
                          class="peer sr-only"
                        />
                        <label
                          for="compound-monthly"
                          class="flex items-center justify-center py-3 px-4 border border-gray-300 rounded-md cursor-pointer peer-checked:border-primary peer-checked:bg-primary/5 hover:bg-gray-50 transition-colors duration-200"
                        >
                          <i class="fa fa-calendar-o mr-2"></i> 每月
                        </label>
                      </div>
                      <div class="relative">
                        <input
                          type="radio"
                          id="compound-quarterly"
                          name="compound-frequency"
                          value="quarterly"
                          class="peer sr-only"
                        />
                        <label
                          for="compound-quarterly"
                          class="flex items-center justify-center py-3 px-4 border border-gray-300 rounded-md cursor-pointer peer-checked:border-primary peer-checked:bg-primary/5 hover:bg-gray-50 transition-colors duration-200"
                        >
                          <i class="fa fa-calendar mr-2"></i> 每季度
                        </label>
                      </div>
                      <div class="relative">
                        <input
                          type="radio"
                          id="compound-annually"
                          name="compound-frequency"
                          value="annually"
                          class="peer sr-only"
                        />
                        <label
                          for="compound-annually"
                          class="flex items-center justify-center py-3 px-4 border border-gray-300 rounded-md cursor-pointer peer-checked:border-primary peer-checked:bg-primary/5 hover:bg-gray-50 transition-colors duration-200"
                        >
                          <i class="fa fa-calendar-check-o mr-2"></i> 每年
                        </label>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 通货膨胀率 -->
                <div>
                  <label for="inflation-rate" class="block text-sm font-medium text-gray-700 mb-1"
                    >预计通货膨胀率 (%)</label
                  >
                  <div class="relative">
                    <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-gray-500">
                      <i class="fa fa-line-chart"></i>
                    </span>
                    <input
                      type="number"
                      id="inflation-rate"
                      name="inflation-rate"
                      min="0"
                      max="10"
                      step="0.1"
                      value="2.0"
                      class="pl-10 block w-full rounded-md border-gray-300 shadow-sm focus:outline-none input-focus py-3 px-4 border"
                    />
                  </div>
                </div>

                <!-- 提交按钮 -->
                <div class="flex justify-end space-x-4 pt-4">
                  <button
                    type="button"
                    id="reset-btn"
                    class="px-6 py-3 border border-gray-300 rounded-md shadow-sm text-base font-medium text-gray-700 bg-white hover:bg-gray-50 transition-colors duration-200 btn-hover"
                  >
                    <i class="fa fa-refresh mr-2"></i> 重置
                  </button>
                  <button
                    type="submit"
                    class="px-6 py-3 border border-transparent rounded-md shadow-sm text-base font-medium text-white bg-primary hover:bg-primary/90 transition-colors duration-200 btn-hover"
                  >
                    <i class="fa fa-calculator mr-2"></i> 计算
                  </button>
                </div>
              </form>
            </div>
          </div>

          <!-- 结果卡片 -->
          <div class="lg:col-span-1">
            <div class="bg-white rounded-xl shadow-lg p-6 md:p-8 card-shadow h-full flex flex-col">
              <h2 class="text-xl font-bold text-neutral mb-6 flex items-center">
                <i class="fa fa-bar-chart text-primary mr-2"></i> 计算结果
              </h2>

              <div id="results-container" class="flex-grow space-y-6">
                <!-- 结果为空时显示 -->
                <div
                  id="empty-results"
                  class="flex flex-col items-center justify-center h-64 text-gray-500"
                >
                  <i class="fa fa-calculator text-5xl mb-4 text-gray-300"></i>
                  <p class="text-center">请输入您的储蓄信息并点击"计算"</p>
                </div>

                <!-- 计算结果区域 -->
                <div id="calculation-results" class="hidden space-y-6">
                  <!-- 目标时间和金额 -->
                  <div class="space-y-4">
                    <div class="p-4 bg-primary/5 rounded-lg border border-primary/20">
                      <h3 class="font-medium text-primary mb-2">目标达成预测</h3>
                      <div class="grid grid-cols-2 gap-2">
                        <div>
                          <p class="text-sm text-gray-500">目标时间</p>
                          <p id="result-time" class="text-xl font-bold text-neutral">-</p>
                        </div>
                        <div>
                          <p class="text-sm text-gray-500">预计金额</p>
                          <p id="result-amount" class="text-xl font-bold text-primary">-</p>
                        </div>
                      </div>
                    </div>

                    <!-- 进度条 -->
                    <div>
                      <div class="flex justify-between mb-1">
                        <span class="text-sm font-medium text-gray-700">储蓄进度</span>
                        <span id="progress-percentage" class="text-sm font-medium text-primary"
                          >0%</span
                        >
                      </div>
                      <div class="w-full bg-gray-200 rounded-full h-2.5">
                        <div
                          id="progress-bar"
                          class="bg-primary h-2.5 rounded-full"
                          style="width: 0%"
                        ></div>
                      </div>
                    </div>
                  </div>

                  <!-- 详细结果 -->
                  <div class="space-y-4">
                    <div class="grid grid-cols-2 gap-4">
                      <div class="bg-white p-4 rounded-lg border border-gray-200">
                        <p class="text-sm text-gray-500">本金总额</p>
                        <p id="principal-amount" class="text-lg font-bold text-neutral">-</p>
                      </div>
                      <div class="bg-white p-4 rounded-lg border border-gray-200">
                        <p class="text-sm text-gray-500">利息收益</p>
                        <p id="interest-amount" class="text-lg font-bold text-secondary">-</p>
                      </div>
                    </div>

                    <div class="bg-white p-4 rounded-lg border border-gray-200">
                      <p class="text-sm text-gray-500">通货膨胀影响</p>
                      <p id="inflation-effect" class="text-lg font-bold text-accent">-</p>
                    </div>

                    <div class="bg-white p-4 rounded-lg border border-gray-200">
                      <p class="text-sm text-gray-500">实际购买力</p>
                      <p id="real-value" class="text-lg font-bold text-neutral">-</p>
                    </div>
                  </div>

                  <!-- 图表容器 -->
                  <div class="mt-4">
                    <h3 class="font-medium text-gray-700 mb-3">储蓄增长趋势</h3>
                    <div class="h-64">
                      <canvas id="growth-chart"></canvas>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 建议区域 -->
              <div id="recommendations" class="mt-6 pt-6 border-t border-gray-200 hidden">
                <h3 class="font-medium text-gray-700 mb-3">个性化建议</h3>
                <div id="recommendation-text" class="text-gray-600 space-y-2">
                  <!-- 建议内容将在这里动态生成 -->
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 财务规划提示 -->
        <div class="mt-12 bg-white rounded-xl shadow-lg p-6 md:p-8 card-shadow">
          <h2 class="text-xl font-bold text-neutral mb-4 flex items-center">
            <i class="fa fa-lightbulb-o text-primary mr-2"></i> 存款规划小贴士
          </h2>
          <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
            <div class="p-4 bg-primary/5 rounded-lg border border-primary/20">
              <h3 class="font-medium text-primary mb-2 flex items-center">
                <i class="fa fa-percent mr-2"></i> 提高存款比例
              </h3>
              <p class="text-gray-600">
                尝试将收入的至少20%用于储蓄，逐步提高存款比例可以加速实现您的财务目标。
              </p>
            </div>
            <div class="p-4 bg-secondary/5 rounded-lg border border-secondary/20">
              <h3 class="font-medium text-secondary mb-2 flex items-center">
                <i class="fa fa-line-chart mr-2"></i> 投资增值
              </h3>
              <p class="text-gray-600">
                考虑将一部分储蓄投资于低风险理财产品或指数基金，长期来看可能获得更高回报。
              </p>
            </div>
            <div class="p-4 bg-accent/5 rounded-lg border border-accent/20">
              <h3 class="font-medium text-accent mb-2 flex items-center">
                <i class="fa fa-calendar-check-o mr-2"></i> 定期复盘
              </h3>
              <p class="text-gray-600">
                每月定期检查您的财务状况，根据实际情况调整存款计划，确保目标可实现。
              </p>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-neutral text-white py-8">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
          <div>
            <h3 class="text-lg font-bold mb-4">财务规划助手</h3>
            <p class="text-gray-400">帮助您实现财务目标，规划美好未来</p>
          </div>
          <div>
            <h3 class="text-lg font-bold mb-4">工具</h3>
            <ul class="space-y-2">
              <li>
                <a href="#" class="text-gray-400 hover:text-white transition-colors duration-200"
                  >存款目标计算器</a
                >
              </li>
              <li>
                <a href="#" class="text-gray-400 hover:text-white transition-colors duration-200"
                  >退休规划工具</a
                >
              </li>
              <li>
                <a href="#" class="text-gray-400 hover:text-white transition-colors duration-200"
                  >贷款还款计算器</a
                >
              </li>
              <li>
                <a href="#" class="text-gray-400 hover:text-white transition-colors duration-200"
                  >投资回报计算器</a
                >
              </li>
            </ul>
          </div>
          <div>
            <h3 class="text-lg font-bold mb-4">资源</h3>
            <ul class="space-y-2">
              <li>
                <a href="#" class="text-gray-400 hover:text-white transition-colors duration-200"
                  >财务知识</a
                >
              </li>
              <li>
                <a href="#" class="text-gray-400 hover:text-white transition-colors duration-200"
                  >理财技巧</a
                >
              </li>
              <li>
                <a href="#" class="text-gray-400 hover:text-white transition-colors duration-200"
                  >投资指南</a
                >
              </li>
              <li>
                <a href="#" class="text-gray-400 hover:text-white transition-colors duration-200"
                  >常见问题</a
                >
              </li>
            </ul>
          </div>
          <div>
            <h3 class="text-lg font-bold mb-4">联系我们</h3>
            <ul class="space-y-2">
              <li class="flex items-center">
                <i class="fa fa-envelope-o mr-2 text-gray-400"></i>
                <a
                  href="mailto:support@example.com"
                  class="text-gray-400 hover:text-white transition-colors duration-200"
                  >support@example.com</a
                >
              </li>
              <li class="flex items-center">
                <i class="fa fa-phone mr-2 text-gray-400"></i>
                <a
                  href="tel:+8612345678901"
                  class="text-gray-400 hover:text-white transition-colors duration-200"
                  >+86 123 4567 8901</a
                >
              </li>
            </ul>
            <div class="mt-4 flex space-x-4">
              <a href="#" class="text-gray-400 hover:text-white transition-colors duration-200">
                <i class="fa fa-weibo text-xl"></i>
              </a>
              <a href="#" class="text-gray-400 hover:text-white transition-colors duration-200">
                <i class="fa fa-wechat text-xl"></i>
              </a>
              <a href="#" class="text-gray-400 hover:text-white transition-colors duration-200">
                <i class="fa fa-qq text-xl"></i>
              </a>
            </div>
          </div>
        </div>
        <div class="mt-8 pt-6 border-t border-gray-700 text-center text-gray-400">
          <p>© 2025 财务规划助手. 保留所有权利.</p>
        </div>
      </div>
    </footer>

    <script>
      // 等待DOM加载完成
      document.addEventListener('DOMContentLoaded', function () {
        // 获取表单和相关元素
        const form = document.getElementById('savings-form')
        const resetBtn = document.getElementById('reset-btn')
        const emptyResults = document.getElementById('empty-results')
        const calculationResults = document.getElementById('calculation-results')
        const recommendations = document.getElementById('recommendations')
        const compoundComparison = document.getElementById('compound-comparison')

        // 图表变量
        let growthChart = null

        // 表单提交事件
        form.addEventListener('submit', function (e) {
          e.preventDefault()
          calculateSavings()
        })

        // 重置按钮事件
        resetBtn.addEventListener('click', function () {
          form.reset()
          emptyResults.classList.remove('hidden')
          calculationResults.classList.add('hidden')
          recommendations.classList.add('hidden')

          // 销毁图表
          if (growthChart) {
            growthChart.destroy()
            growthChart = null
          }
        })

        // 计算存款结果
        function calculateSavings() {
          // 获取表单值
          const goalAmount = parseFloat(document.getElementById('goal-amount').value) || 0
          const currentSavings = parseFloat(document.getElementById('current-savings').value) || 0
          const monthlyContribution =
            parseFloat(document.getElementById('monthly-contribution').value) || 0
          const annualInterest = parseFloat(document.getElementById('annual-interest').value) || 0
          const timeframe = parseFloat(document.getElementById('timeframe').value) || 0
          const inflationRate = parseFloat(document.getElementById('inflation-rate').value) || 0

          // 获取复利计算方式
          let compoundFrequency = 'monthly'
          if (document.getElementById('compound-quarterly').checked) {
            compoundFrequency = 'quarterly'
          } else if (document.getElementById('compound-annually').checked) {
            compoundFrequency = 'annually'
          }

          // 计算未来价值（使用所选复利方式）
          const futureValue = calculateFutureValue(
            currentSavings,
            monthlyContribution,
            annualInterest,
            timeframe,
            compoundFrequency
          )

          // 计算复利方式对比
          const compoundComparisons = calculateCompoundComparisons(
            currentSavings,
            monthlyContribution,
            annualInterest,
            timeframe
          )

          // 计算本金总额
          const principal = currentSavings + monthlyContribution * 12 * timeframe

          // 计算利息收益
          const interest = futureValue - principal

          // 计算通货膨胀影响
          const inflationFactor = Math.pow(1 + inflationRate / 100, timeframe)
          const realValue = futureValue / inflationFactor
          const inflationEffect = futureValue - realValue

          // 计算达成百分比
          let progressPercentage = (futureValue / goalAmount) * 100
          if (progressPercentage > 100) {
            progressPercentage = 100
          }

          // 显示结果
          displayResults({
            futureValue,
            principal,
            interest,
            inflationEffect,
            realValue,
            progressPercentage,
            timeframe,
            goalAmount,
            monthlyContribution,
            annualInterest
          })

          // 显示图表
          displayChart({
            currentSavings,
            monthlyContribution,
            annualInterest,
            timeframe,
            compoundFrequency
          })

          // 显示复利对比
          displayCompoundComparison(compoundComparisons, annualInterest)

          // 显示建议
          displayRecommendations({
            futureValue,
            goalAmount,
            timeframe,
            monthlyContribution,
            annualInterest
          })
        }

        // 计算未来价值
        function calculateFutureValue(
          currentSavings,
          monthlyContribution,
          annualInterest,
          timeframe,
          compoundFrequency
        ) {
          // 计算复利期数和利率
          let periodsPerYear, ratePerPeriod
          switch (compoundFrequency) {
            case 'monthly':
              periodsPerYear = 12
              break
            case 'quarterly':
              periodsPerYear = 4
              break
            case 'annually':
              periodsPerYear = 1
              break
            default:
              periodsPerYear = 12
          }

          // 计算总期数和每期利率
          const totalPeriods = timeframe * periodsPerYear
          ratePerPeriod = annualInterest / 100 / periodsPerYear

          // 计算未来价值（复利公式）
          let futureValue
          if (ratePerPeriod === 0) {
            // 无利息情况
            futureValue = currentSavings + monthlyContribution * 12 * timeframe
          } else {
            // 有利息情况
            futureValue = currentSavings * Math.pow(1 + ratePerPeriod, totalPeriods)

            // 计算定期存款的未来价值（年金终值公式）
            // 转换为每期存款金额
            const contributionPerPeriod = (monthlyContribution * 12) / periodsPerYear

            if (ratePerPeriod === 0) {
              futureValue += contributionPerPeriod * totalPeriods
            } else {
              futureValue +=
                contributionPerPeriod *
                ((Math.pow(1 + ratePerPeriod, totalPeriods) - 1) / ratePerPeriod)
            }
          }

          return futureValue
        }

        // 计算不同复利方式的对比
        function calculateCompoundComparisons(
          currentSavings,
          monthlyContribution,
          annualInterest,
          timeframe
        ) {
          return {
            monthly: calculateFutureValue(
              currentSavings,
              monthlyContribution,
              annualInterest,
              timeframe,
              'monthly'
            ),
            quarterly: calculateFutureValue(
              currentSavings,
              monthlyContribution,
              annualInterest,
              timeframe,
              'quarterly'
            ),
            annually: calculateFutureValue(
              currentSavings,
              monthlyContribution,
              annualInterest,
              timeframe,
              'annually'
            )
          }
        }

        // 显示计算结果
        function displayResults(results) {
          // 隐藏空结果，显示计算结果
          emptyResults.classList.add('hidden')
          calculationResults.classList.remove('hidden')
          recommendations.classList.remove('hidden')

          // 格式化货币
          const formatCurrency = (value) => {
            return (
              '¥' +
              value.toLocaleString('zh-CN', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
              })
            )
          }

          // 设置结果值
          document.getElementById('result-time').textContent = results.timeframe + ' 年'
          document.getElementById('result-amount').textContent = formatCurrency(results.futureValue)
          document.getElementById('principal-amount').textContent = formatCurrency(
            results.principal
          )
          document.getElementById('interest-amount').textContent = formatCurrency(results.interest)
          document.getElementById('inflation-effect').textContent = formatCurrency(
            results.inflationEffect
          )
          document.getElementById('real-value').textContent = formatCurrency(results.realValue)
          document.getElementById('progress-percentage').textContent =
            Math.round(results.progressPercentage) + '%'
          document.getElementById('progress-bar').style.width = results.progressPercentage + '%'
        }

        // 显示图表
        function displayChart(params) {
          const {
            currentSavings,
            monthlyContribution,
            annualInterest,
            timeframe,
            compoundFrequency
          } = params

          // 销毁现有图表
          if (growthChart) {
            growthChart.destroy()
            growthChart = null
          }

          // 计算每月的余额（使用所选复利方式）
          const monthlyRate = annualInterest / 100 / 12
          const months = Math.round(timeframe * 12)
          const labels = []
          const data = []

          let balance = currentSavings
          data.push(balance)
          labels.push('初始')

          for (let i = 1; i <= months; i++) {
            // 计算当月利息
            const interest = balance * monthlyRate

            // 更新余额
            balance += interest + monthlyContribution

            // 存储数据
            data.push(balance)

            // 每3个月显示一个标签
            if (i % 3 === 0 || i === months) {
              const year = Math.floor(i / 12)
              const month = i % 12
              let label

              if (month === 0) {
                label = `第 ${year} 年`
              } else {
                label = `第 ${year} 年 ${month} 月`
              }

              labels.push(label)
            } else {
              labels.push('')
            }
          }

          // 创建图表
          const ctx = document.getElementById('growth-chart').getContext('2d')
          growthChart = new Chart(ctx, {
            type: 'line',
            data: {
              labels: labels,
              datasets: [
                {
                  label: '存款余额',
                  data: data,
                  borderColor: '#165DFF',
                  backgroundColor: 'rgba(22, 93, 255, 0.1)',
                  borderWidth: 2,
                  tension: 0.3,
                  fill: true
                }
              ]
            },
            options: {
              responsive: true,
              maintainAspectRatio: false,
              plugins: {
                legend: {
                  display: false
                },
                tooltip: {
                  backgroundColor: 'rgba(255, 255, 255, 0.9)',
                  titleColor: '#3D4451',
                  bodyColor: '#3D4451',
                  borderColor: '#E2E8F0',
                  borderWidth: 1,
                  padding: 12,
                  displayColors: false,
                  callbacks: {
                    label: function (context) {
                      return (
                        '存款余额: ¥' +
                        context.raw.toLocaleString('zh-CN', {
                          minimumFractionDigits: 2,
                          maximumFractionDigits: 2
                        })
                      )
                    }
                  }
                }
              },
              scales: {
                x: {
                  grid: {
                    display: false
                  }
                },
                y: {
                  beginAtZero: true,
                  ticks: {
                    callback: function (value) {
                      return '¥' + value.toLocaleString('zh-CN')
                    }
                  }
                }
              }
            }
          })
        }

        // 显示复利对比表格
        function displayCompoundComparison(comparisons, annualInterest) {
          // 清空表格
          compoundComparison.innerHTML = ''

          // 获取本金总额
          const principal = parseFloat(document.getElementById('current-savings').value) || 0
          const monthlyContribution =
            parseFloat(document.getElementById('monthly-contribution').value) || 0
          const timeframe = parseFloat(document.getElementById('timeframe').value) || 0
          const totalPrincipal = principal + monthlyContribution * 12 * timeframe

          // 格式化货币
          const formatCurrency = (value) => {
            return (
              '¥' +
              value.toLocaleString('zh-CN', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
              })
            )
          }

          // 确定基准复利方式（默认为每月）
          const baseMethod = comparisons.monthly

          // 添加每种复利方式的行
          const methods = [
            { name: '每月复利', value: comparisons.monthly },
            { name: '每季度复利', value: comparisons.quarterly },
            { name: '每年复利', value: comparisons.annually }
          ]

          methods.forEach((method) => {
            const row = document.createElement('tr')

            // 复利方式
            const methodCell = document.createElement('td')
            methodCell.className = 'px-4 py-3 whitespace-nowrap'
            methodCell.innerHTML = `
                <div class="flex items-center">
                    <div class="ml-4">
                        <div class="text-sm font-medium text-gray-900">${method.name}</div>
                    </div>
                </div>
            `

            // 到期金额
            const amountCell = document.createElement('td')
            amountCell.className =
              'px-4 py-3 whitespace-nowrap text-right text-sm font-medium text-gray-900'
            amountCell.textContent = formatCurrency(method.value)

            // 利息差异
            const diffCell = document.createElement('td')
            diffCell.className = 'px-4 py-3 whitespace-nowrap text-right text-sm text-gray-900'

            // 计算与基准方式的差异
            const interestDiff = method.value - baseMethod

            if (interestDiff > 0) {
              diffCell.innerHTML = `<span class="text-green-600">+${formatCurrency(interestDiff)}</span>`
            } else if (interestDiff < 0) {
              diffCell.innerHTML = `<span class="text-red-600">${formatCurrency(interestDiff)}</span>`
            } else {
              diffCell.textContent = '0'
            }

            // 添加单元格到行
            row.appendChild(methodCell)
            row.appendChild(amountCell)
            row.appendChild(diffCell)

            // 添加行到表格
            compoundComparison.appendChild(row)
          })
        }

        // 显示个性化建议
        function displayRecommendations(params) {
          const { futureValue, goalAmount, timeframe, monthlyContribution, annualInterest } = params
          const recommendationText = document.getElementById('recommendation-text')

          // 清空建议区域
          recommendationText.innerHTML = ''

          // 计算差距
          const gap = goalAmount - futureValue
          const isGoalMet = futureValue >= goalAmount

          // 基本建议
          if (isGoalMet) {
            recommendationText.innerHTML += `
                <p class="flex items-start">
                    <i class="fa fa-check-circle text-green-500 mt-1 mr-2"></i>
                    <span>恭喜！按照当前的储蓄计划，您将能够实现目标。您的存款将比目标多${formatCurrency(gap * -1)}。</span>
                </p>
            `
          } else {
            recommendationText.innerHTML += `
                <p class="flex items-start">
                    <i class="fa fa-info-circle text-blue-500 mt-1 mr-2"></i>
                    <span>按照当前的储蓄计划，您将在${timeframe}年后积累${formatCurrency(futureValue)}，距离目标还差${formatCurrency(gap)}。</span>
                </p>
            `
          }

          // 提高存款金额的建议
          if (!isGoalMet) {
            // 计算需要达到目标的每月存款
            let requiredMonthly = monthlyContribution
            let calculatedValue = futureValue

            while (calculatedValue < goalAmount && requiredMonthly < monthlyContribution * 3) {
              requiredMonthly += 100
              calculatedValue = calculateFutureValue(
                parseFloat(document.getElementById('current-savings').value) || 0,
                requiredMonthly,
                annualInterest,
                timeframe,
                document.querySelector('input[name="compound-frequency"]:checked').value
              )
            }

            if (requiredMonthly > monthlyContribution) {
              recommendationText.innerHTML += `
                    <p class="flex items-start">
                        <i class="fa fa-lightbulb-o text-yellow-500 mt-1 mr-2"></i>
                        <span>若想实现目标，您可以考虑将每月存款提高到${formatCurrency(requiredMonthly)}，或者延长储蓄时间。</span>
                    </p>
                `
            }
          }

          // 关于利率的建议
          if (annualInterest < 4) {
            recommendationText.innerHTML += `
                <p class="flex items-start">
                    <i class="fa fa-line-chart text-purple-500 mt-1 mr-2"></i>
                    <span>当前年利率较低，您可以考虑将一部分存款投资于低风险理财产品或指数基金，以获得更高的回报。</span>
                </p>
            `
          }

          // 关于通货膨胀的建议
          const inflationRate = parseFloat(document.getElementById('inflation-rate').value) || 0
          if (inflationRate > 0 && timeframe > 5) {
            recommendationText.innerHTML += `
                <p class="flex items-start">
                    <i class="fa fa-exclamation-triangle text-red-500 mt-1 mr-2"></i>
                    <span>由于通货膨胀的影响，${timeframe}年后的${formatCurrency(futureValue)}的实际购买力仅相当于现在的${formatCurrency(parseFloat(document.getElementById('real-value').textContent.replace(/[^0-9.]/g, '')))}。考虑投资以应对通货膨胀。</span>
                </p>
            `
          }

          // 关于复利方式的建议
          const currentCompound = document.querySelector(
            'input[name="compound-frequency"]:checked'
          ).value
          if (currentCompound !== 'monthly') {
            recommendationText.innerHTML += `
                <p class="flex items-start">
                    <i class="fa fa-refresh text-teal-500 mt-1 mr-2"></i>
                    <span>复利频率越高，最终收益越大。选择"每月复利"可以获得更多的利息收益。</span>
                </p>
            `
          }

          // 格式化货币
          function formatCurrency(value) {
            return (
              '¥' +
              value.toLocaleString('zh-CN', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
              })
            )
          }
        }
      })
    </script>
  </body>
</html>
